<template>
  <div v-loading="loading">
    <GoBack></GoBack>
    <ARow class="enter-x">
      <ACol :span="24">
        <Card class="card-brief">
          <div :class="`${prefixCls}-header`">
            <div class="info">
              <div :class="`${prefixCls}-header-img`">
                <img :src="idpConnectTmpl.logo" width="50px" height="50px"/>
              </div>
              <Description style="width: 100%" @register="registerDescription" />
            </div>
            <div>
               <a-button
                  type="primary" class="mr-3 mb-2"
                  v-if="idpConnectList.length >= 1"
                  @click="handleAddIdpConnect"
               >
                 添加登录连接
               </a-button>
            </div>
          </div>
        </Card>
      </ACol>

      <ACol :span="24">
        <Card class="mt-2 card-brief" >
          <div :class="`${prefixCls}-account-detail`" v-if="idpConnectList.length >= 1">
            <Tabs 
              v-model:activeKey="activeKey" 
              :destroy-inactive-tab-pane="true" 
              :tabBarGutter="20" :tabBarStyle="tabBarStyle" 
              @change="handleChange" animated
            >
              <TabPane v-for="(item, index) in getTabList" :tab="item.tabName" :key="index">
                <InputForm
                  :connect-tmpl="idpConnectTmpl" :idpId="idpId"
                  :idp-connect="item" @save="handleSaveIdpConnect"
                  :index="index" @delete="handleDeleteIdpConnect"
                />
              </TabPane>
            </Tabs>
          </div>
          <InputForm
            v-else :connect-tmpl="idpConnectTmpl" :idpId="idpId"
            :index="-1" @save="handleSaveIdpConnect"
          />
        </Card>
      </ACol>
    </ARow>

  </div>
</template>
<script lang="ts" setup>
  import { ref, useAttrs, onMounted, computed } from "vue"
  import { Space, Upload, Avatar, Tabs, TabPane } from "ant-design-vue"
  import { useDesign } from "/@/hooks/web/useDesign"
  import InputForm from "./form/index.vue"
  import { useGlobSetting } from "/@/hooks/setting"
  import { connectTmplDescSchema } from "./data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import * as extIdpApi from "/@/api/iam/extIdp"
  import GoBack from '/@/components/GoBack'
  import { useRoute, useRouter } from "vue-router"
  import { Card, Col, Row } from "ant-design-vue"
  import { Description, useDescription } from "/@/components/Description/index"

  const router = useRouter()
  let idpId = router.currentRoute.value.query?.idpId as string
  let idpConnectTmplId = router.currentRoute.value.params?.idpConnectTmplId
  let idpTmplId = router.currentRoute.value.params?.idpTmplId

  const ACol = Col
  const ARow = Row
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const idpConnectTmpl = ref<any>({})
  const { prefixCls } = useDesign("ext-idp-connect")
  const loading = ref(false)
  const activeKey = ref(null)
  const idpConnectList = ref<any[]>([])
  const tabBarStyle = ref({
    marginTop: "-10px",
  })

  const [registerDescription] = useDescription({
    bordered: false,
    data: idpConnectTmpl,
    schema: connectTmplDescSchema,
  })

  const { createMessage } = useMessage()
  const glob = useGlobSetting()

  const getTabList = computed(() => {
    const length = idpConnectList.value.length
    const newTabName = idpConnectTmpl.value.name + length
    const tabList = idpConnectList.value.map(idpConnect => {
      return {
        ...idpConnect,
        tabName: idpConnect?.displayName || newTabName,
      }
    })
    if (!activeKey.value) {
      activeKey.value = tabList[0].tabKey
    }
    return tabList;
  })

  const handleChange = (value) => {
    console.log(value)
  }

  const handleSaveIdpConnect = async (index, data) => {
    if (index < 0) {
      await loadIdpConnect()
    } else {
      idpConnectList.value[index] = data
    }
  }

  const handleDeleteIdpConnect = async (index) => {
    idpConnectList.value.splice(index, 1);
  }

  const handleAddIdpConnect = () => {
    if (idpConnectList.value.findIndex(item => !item.id) > 0) {
      createMessage.warn("一次只能添加一个身份源连接，请先保存")
      return
    }
    idpConnectList.value.push({})
  }
  const loadIdpConnect = async () => {
    loading.value = true
    try {
      idpConnectList.value = await extIdpApi.listIdpConnect({ idpId: idpId, connectTmplId: idpConnectTmplId })
      extIdpApi.getIdpTmpl({ id: idpTmplId }).then((idpTmpl) => {
        if (!idpTmpl) {
          createMessage.error('身份源不存在')
          return
        }
        idpConnectTmpl.value = idpTmpl.connectTmpls?.find(e => e.id == idpConnectTmplId)
      }).finally(() => {
        loading.value = false
      })
    } catch (e) {
      console.error(e)
      loading.value = false
    }
  }
  onMounted(async () => {
    await loadIdpConnect()
  })

</script>

<style lang="less">
  @prefix-cls: ~"@{namespace}-ext-idp-connect";

  .@{prefix-cls} {

    &-header .info {
      display: flex;
      width: 80%;
    }

    &-header {
      display: flex;
      width: 100%;
      justify-content: space-between;
    }

    &-header-img {
      margin-right: 15px;
    }
  }
</style>
